package com.ah.util;
import java.io.*;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class MyListener implements ServletContextListener {
	private File getFile(ServletContext context) {
		String path = context.getRealPath("/");
		File file = new File(path + "/save.txt");
		if (!file.exists()) {
			try {
				file.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		System.out.println("file:" + file.getAbsolutePath());
		return file;
	}
	@Override
	public void contextInitialized(ServletContextEvent e) {
		BufferedReader br;
		int count = 0;
		try {
			// 读取文件
			ServletContext context = e.getServletContext();
			File file = getFile(context);
			br = new BufferedReader(new FileReader(file));
			String readLine = br.readLine();
			// 转换成数值类型
			if (readLine == null) {
				readLine = "0";
			}
			count = Integer.parseInt(readLine);
			context.setAttribute("count", count);
			System.out.println("--------Read count:" + count);
		} catch (NumberFormatException e1) {
			e1.printStackTrace();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
	}
	@Override
	public void contextDestroyed(ServletContextEvent e) {
		ServletContext ct = e.getServletContext();
		Integer count = (Integer) ct.getAttribute("count");
		count = 3999;// --模拟
		// 写入文件
		try {
			File file = getFile(ct);
			BufferedWriter bw;
			bw = new BufferedWriter(new FileWriter(file));
			bw.write(count.toString());
			bw.close();
		} catch (IOException ec) {
			ec.printStackTrace();
		}
	}
}
